<template>
  <!-- 返回首页 -->
  <!-- 返回上一个页面/home/index -->
  <van-nav-bar style="background-color: #3172ea; display: block">
    <template #left>
      <div @click="$router.push('/home/index')" style="color: white">
        <van-icon name="arrow-left" size="18" color="#fff" />
        <span style="font-size: 16px; line-height: 20px">预约体检</span>
        <!-- <van-icon name="" size="18"></van-icon> -->
      </div>
    </template>
  </van-nav-bar>
  <div class="main">
    <!--地区选择/搜索  -->
    <div class="location_search">
      <span @click="showTan">{{ xZlocation }}<i></i></span>

      <van-popup v-model:show="show" position="bottom" :style="{ height: '60%', paddingTop: '20px' }">
        <van-picker title="标题" v-model="xZlocationID" :columns="items" @cancel="showTan" @confirm="onConfirm" />
      </van-popup>

      <form action="/">
        <van-search @click-left-icon="selectHospital" @update:model-value="timeSelectHospital" @search="selectHospital"
          v-model="h_name" background="transparent" placeholder="请输入搜索关键词" />
      </form>
    </div>
    <!--地区选择/搜索 完  -->
    <!-- 选项菜单 开始 -->
    <!-- 逐渐方式 -->
    <van-grid :border="false" square :column-num="4" style="border-radius: 5px">
      <van-grid-item :key="value">
        <i class="iconfont icon-zhiyejiankang" @click="QueryTiJianTanCan(1, '入职体检')"
          style="font-size: 40px; color: #387af4"></i>
        <span>入职体检</span>
      </van-grid-item>
      <van-grid-item :key="value">
        <i class="iconfont icon-old" @click="QueryTiJianTanCan(2, '老年体检')" style="font-size: 40px; color: #387af4"></i>
        <span>老年体检</span>
      </van-grid-item>
      <van-grid-item :key="value">
        <i class="iconfont icon-ertong" @click="QueryTiJianTanCan(3, '儿童体检')" style="font-size: 40px; color: #387af4"></i>
        <span>儿童体检</span>
      </van-grid-item>
      <van-grid-item :key="value">
        <i class="iconfont icon-yunfu" @click="QueryTiJianTanCan(4, '婚检孕检')" style="font-size: 40px; color: #387af4"></i>
        <span>婚检孕检</span>
      </van-grid-item>
    </van-grid>
    <!-- 选项菜单 结束 -->
    <!-- 体检前测评/条件记录 -->
    <div class="menu_option_tow">
      <div class="front">
        <div>检前测评</div>
        <p>那些检查适合你</p>
      </div>
      <div class="later">
        <div>体检记录</div>
        <p>查订单/开发票</p>
      </div>
    </div>
    <!-- 体检前测评/条件记录 结束-->
    <div class="advertising"></div>
    <!-- 广告结束 -->
    <!-- 推荐机构列表 -->
    <div class="organization_list" :style="hospitals.length < 4 ? 'height:400px' : ''">
      <div class="title">推荐机构</div>
      <div class="background-white">
        <!-- 下拉菜单 -->
        <!-- <van-dropdown-menu>
          <van-dropdown-item v-model="value1" :options="option1" @change="TiJianSelect" />
        </van-dropdown-menu> -->
        <!-- @click-tab="onClickTab" -->
        <van-tabs v-model:active="active" @click-tab="TiJianSelect" style="margin-bottom: 20px;">
          <van-tab v-for="item in option1" :name="item.value" :title="item.text"></van-tab>
        </van-tabs>
      </div>

      <van-list v-if="hospitals.length" v-model:loading="loading" :finished="finished" finished-text="没有更多了"
        @load="onLoad">
        <template v-for="hospitalItem in hospitals" :key="hospitalItem.h_id">
          <HospitalList :yiyuan="hospitalItem" @click="$router.push('/hospital_Details/' + hospitalItem.h_id)">
          </HospitalList>
        </template>
        <van-cell />
      </van-list>
      <div v-else style="text-align: center; color: #999">暂无数据...</div>
    </div>
    <!-- 推荐列表机构 结束 -->
    <!-- 显示体检套餐信息 -->
    <van-popup v-model:show="taoCanShow" position="bottom" :style="{ height: '100%' }">
      <van-nav-bar style="background-color: #3172ea; display: block">
        <template #left>
          <div @click="taoCanShow = false" style="color: white">
            <van-icon name="arrow-left" size="18" color="#fff" />
            <span style="font-size: 16px; line-height: 20px">{{
              textTanCan
            }}</span>
          </div>
        </template>
      </van-nav-bar>
      <!-- 套餐列表 -->
      <div class="tao-can-list">
        <van-list v-model:loading="loadingTancan" :finished="true" finished-text="没有更多了">
          <van-cell v-for="item in tiJianTanCan" :key="item.s_id">
            <div class="item" @click="$router.push('/set_meal_details/' + item.s_id)">
              <img :src="item.s_cover" alt="" />
              <div>
                <p>{{ item.s_title }}</p>
                <span>￥{{ item.s_price }}</span>
              </div>
            </div>
            <!-- {{ item }} -->
          </van-cell>
        </van-list>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import router from "@/router";
import { ref, onMounted, reactive, onBeforeMount, watch } from "vue";
import httpApi from "@/http";
import { locationB, locationA, hospital, taocanType } from "@/type/Location";
import { showFailToast, showNotify, showToast } from "vant";
// 保存将服务端返回的数据经行处理之后的数据
let items: any;
// 保存请求到的地区数据
let location: any;
// 保存当前选中的地区数据
let xZlocation: any = "全部";
// 保存当前地区的id
let xZlocationID: any = ref([-1]);

onMounted(() => {
  // 发请求回去地区数据
  httpApi.examination.eLoactionProvincesAll().then((res) => {
    // console.log("res:", res.data.data);
    location = res.data.data;
    items = location.map((item: { provinces_name: any; provinces_id: any }) => {
      return {
        text: item.provinces_name,
        value: item.provinces_id,
      };
    });
    xZlocation = "全部";
  });
});

// 获取保存医院的信息
let hospitals = ref<hospital[]>([]);
// 当前页数
let hPage = ref<number>(1);
// 每一页数据的数量
let hPageSize = ref<number>(10);
// 数据总量
let total = ref<number>(0);
// 在页面挂在的时候获取所有医院的信息
function queryH(page: number, pagesize: number) {
  // 设置是否在加载状态
  loading.value = true;
  httpApi.examination.eRequestHospitalAll({ page, pagesize }).then((res) => {
    console.log("医院:", res.data.data.result.length);
    hospitals.value.push(...res.data.data.result);
    hPage.value = res.data.data.page + 1;
    hPageSize.value = res.data.data.pagesize;
    total.value = res.data.data.total;
    // console.log(hospitals);
    // console.log('res:', total.value);
    loading.value = false;
    if (total.value < (hPage.value - 1) * hPageSize.value) {
      // console.log(' hPage.value * hPageSize.value:', (hPage.value - 1) * hPageSize.value);
      finished.value = true;
    }
  });
}

// 是否处于加载状态，加载过程中不触发 load 事件
let loading = ref<boolean>(false);
// 是否已加载完成，加载完成后不再触发 load 事件
let finished = ref(false);
// 触底加载
const onLoad = () => {
  // 触底执行请求医院的数据
  loading.value = false;
  if (xZlocation === "全部") queryH(hPage.value, hPageSize.value);
};

onMounted(() => {
  queryH(hPage.value, hPageSize.value);
});

onMounted(() => {
  document.documentElement.scrollTop = 0;
});
//
const onClickLeft = function () {
  router.go(-1);
};
// 当选用户选择地区后点击确定后触发当前方法
function onConfirm({ selectedValues, selectedOptions }: any) {
  console.log(selectedValues, selectedOptions);
  showTan();
  // 将当前选择的地区赋值给xZlocation变量
  xZlocation = location[selectedValues - 1].provinces_name;
  console.log("xZlocation", xZlocation);

  // 根据地区选择医院
  httpApi.examination
    .hospitalByProvince({ h_province: xZlocation })
    .then((res) => {
      console.log("a:", res);
      if (res.data.data.length != 0) {
        hospitals.value.splice(0, hospitals.value.length, ...res.data.data);
        // return
      } else {
        // if(res){
        // showNotify({ type: "primary", message: "当前地区没有响应的医院" });
        showToast({
          icon: "fail",
          message:
            "当前地区没有相应的医院,请重新选择！！！",
          wordBreak: "break-word",
        });
        // showToast("当前地区没有相应的医院");
        // }
      }

      console.log("hospitals:", hospitals.value);
    });
}

let active = ref(0);
// 控制弹出层是否显示
let show = ref(false);
// 控制弹出层是否显示的方法
function showTan() {
  show.value = !show.value;
}
// 下拉菜单
const value1 = ref<number>(0);
const option1 = [
  { text: "默认", value: 0 },
  { text: "降序", value: 1 },
  { text: "升序", value: 2 },
];
// 当下拉选项框发生改变的时候触发
function TiJianSelect({name}:any) {
  // console.log("value1.name:", name);
  // 如果需要改成下拉菜单传递的参数只有一个
  switch (name) {
    case 0: {
      queryH(1, hPageSize.value);
      break;
    }
    case 1: {
      httpApi.examination.hospitalDesc().then((res) => {
        // console.log("降序", res);
        hospitals.value.splice(0, hospitals.value.length, ...res.data.data);
        // console.log("降序医院：", hospitals.value);
      });
    }
    case 2: {
      httpApi.examination.hospitalAsc().then((res) => {
        // console.log("升序", res);
        hospitals.value.splice(0, hospitals.value.length, ...res.data.data);
        // console.log("升序医院:", hospitals.value);
      });
    }
  }
}

// 保存体检套餐信息
let taoCanShow = ref<boolean>(false);
// 保存套餐加载信息
let loadingTancan = ref<any>(false);
// 保存点击的套餐名称
let textTanCan = ref<string>("");
let tiJianTanCan = ref<taocanType[]>([]);
function QueryTiJianTanCan(type: number, text: string) {
  // 点击响应的套餐弹出显示
  taoCanShow.value = true;
  textTanCan.value = text;
  httpApi.examination.queryTiJianSelect({ s_graded: type }).then((res) => {
    tiJianTanCan.value.splice(0, tiJianTanCan.value.length, ...res.data.data);
    loadingTancan.value = false;
    console.log("套餐分类信息:", res.data.data);
  });
}
let value = ref();
let h_name = ref<string>('');
// 模糊查询医院（loading）
function selectHospital() {
  console.log('h_name:', h_name);
  if (h_name.value !== '') {
    finished.value = true
    httpApi.examination.vagueSelectHospitals({ h_name: h_name.value }).then(res => {
      // console.log('ref_h_name:',res);
      if (res.data.data.length == 0) {
        showToast({
          icon: "fail",
          message:
            "没有查询到相关的医院",
          wordBreak: "break-word",
        });
        return
      }
      hospitals.value.splice(0, hospitals.value.length, ...res.data.data)
    });
  } else {
    hPage.value=1
    hospitals.value=[]
    queryH(hPage.value, hPageSize.value)
  }
}

// 
let a: any;
function timeSelectHospital() {
  if (a != '') {
    clearTimeout(a);
  }
  a = setTimeout(() => {
    selectHospital();
  }, 1000);
}
</script>

<style lang="scss" scoped>
@import url("//at.alicdn.com/t/c/font_3903764_mv07nx5ip5.css");
@import url("../../../node_modules/vant/lib/index.css");

* {
  font-size: 14px;
}

p {
  margin: 0;
}

img {
  display: block;
}

.main {
  background: linear-gradient(#e7edf9 20%, #ddd);
  padding: 0 10px;
  // text-align: center;
  justify-content: space-between;

  // 地区选择/搜索  开始
  >.location_search {
    display: flex;
    justify-content: space-between;
    overflow: hidden;
    // height: 50px;
    // .van-dropdown-menu__item{
    //   background-color: transparent;
    // }
    // >select {
    //   height: 24px;
    //   border: none;
    //   overflow: hidden;
    //   margin-top: 13px;
    // }

    >span {
      position: relative;
      text-align: center;
      line-height: 60px;

      >i {
        position: absolute;
        top: 50%;
        width: 0;
        height: 10px;
        border: 5px solid transparent;
        border-top-color: black;
        margin-left: 10px;
      }
    }

    >form {
      border-radius: 5px;
    }
  }

  // 地区选择/搜索  结束
  // 菜单开始

  // 菜单结束
  >.menu_option_tow {
    display: flex;
    justify-content: space-between;
    text-align: start;
    margin-top: 10px;

    >div {
      width: 48%;
      box-sizing: border-box;
      border-radius: 5px;
      padding: 0 10px 20px;

      &.front {
        background: url("@/assets/icon/kapian.png") no-repeat -150% 50%,
          linear-gradient(#dae8fb 60%, #fff);
      }

      &.later {
        background: url("@/assets/icon/kapian.png") no-repeat -150% 50%,
          linear-gradient(#d4eef2 60%, #fefefe);
      }

      >div {
        margin: 5px 0;
        font-size: 20px;
      }

      >p {
        color: #626466;
      }
    }
  }

  // 广告
  .advertising {
    height: 10vh;
    margin-top: 10px;
    background: url("@/assets/img/guanggao.jpg") no-repeat;
    background-size: cover;
    background-position: -50%;
  }

  // 广告结束
  // 推荐机构列表
  .organization_list {
    margin-top: 10px;
    background-color: white;
    border-radius: 5px;
    padding: 10px;

    >.title {
      font-size: 20px;
      margin-bottom: 10px;
    }

    .sort {
      display: flex;
      text-align: center;

      >.item {
        flex: 1;
        vertical-align: middle;

        >.content {
          color: #a19f9d;
        }

        >i {
          padding-left: 5px;
          color: #626466;
        }
      }
    }

    .organization_list_type {
      border: 1px solid #0d7cff;
      border-radius: 10px;
      padding: 0 5px;
      background: #eff1f4;
    }
  }
}

.tao-can-list {
  .item {
    display: flex;
    padding-bottom: 8px;
    border-bottom: 1px solid #ccc;

    >img {
      object-fit: cover;
      width: 15%;
      height: 50px;
      margin-right: 10px;
    }

    >div {
      width: 80%;
      flex-grow: 0;

      >p {
        color: #000;
        font-size: 18px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: left;
      }

      >span {
        display: block;
        text-align: left;
        color: #f87446;
      }
    }
  }
}
</style>